import { createRouter, createWebHistory } from 'vue-router'
import AppLayout from '@/components/layout/AppLayout.vue'
import IndexView from '@/views/IndexView.vue'
import { useTokenStore } from '@/stores/mytoken'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 先进入登录页
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/LoginView.vue'),
    },
    // 再进入首页
    {
      path: '/',
      name: '',
      component: AppLayout,
      // 登录保护 需要登陆验证才能进入首页
      meta: { requiresAuth: true, title: '首页' },
      children: [
        {
          path: '',
          name: 'home',
          // 直接加载 打开页面自动跳转到首页
          component: IndexView,
          meta: { title: '默认页' },
        },
        {
          path: '/menus',
          name: 'menus',
          component: () => import('@/views/menus/MenuIndex.vue'),
          meta: { title: '菜单列表' },
        },
        {
          path: '/resource-category',
          name: 'resource-category',
          component: () => import('@/views/resourse-category/ResourceCategoryIndex.vue'),
          meta: { title: '资源分类' },
        },
        {
          path: '/resources',
          name: 'resources',
          component: () => import('@/views/resources/ResourcesIndex.vue'),
          meta: { title: '资源列表' },
        },
        {
          path: '/roles',
          name: 'roles',
          component: () => import('@/views/roles/RolesIndex.vue'),
          meta: { title: '角色列表' },
        },
        {
          path: '/users',
          name: 'users',
          component: () => import('@/views/users/UsersIndex.vue'),
          meta: { title: '用户管理' },
        },
        {
          path: '/courses',
          name: 'courses',
          component: () => import('@/views/courses/CoursesIndex.vue'),
          meta: { title: '课程管理' },
        },
      ],
    },
    {
      path: '/:xxx(.*)*',
      name: 'ErrorPage',
      // 懒加载 减小页面负荷
      component: () => import('@/views/ErrorPage.vue'),
    },
  ],
})

// 路由守卫 /aa/bb/cc/dd 每一个地址都需要登录判断
router.beforeEach((to, from, next) => {
  const tokenStore = useTokenStore()
  if (to.matched.some((record) => record.meta?.requiresAuth)) {
    // 判断是否登录
    if (!tokenStore.token?.access_token) {
      // 没有accesstoken 跳转到登录页  query传递原本要跳转的地址
      next({ name: 'login', query: { redirect: to.fullPath } })
      return
    }
  }

  // 不要求权限，或者存在token 都可以访问
  next()
})

export default router
